/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rukopisyimport;

import cz.mzk.rehan.commons.Model;
import java.io.FileNotFoundException;
import org.dom4j.DocumentException;
import java.io.File;
import java.util.Properties;
import java.util.logging.Logger;
import cz.mzk.rehan.commons.PropertyLoader;
import rukopisyimport.foxml.AbstractPageBuilder;
import rukopisyimport.foxml.ClassicLinkPageBuilder;
import rukopisyimport.foxml.ImageServerPageBuilder;
import rukopisyimport.foxml.MonographBuilder;

/**
 *
 * @author Martin Rehanek (rehan@mzk.cz)
 */
public class ManuscriptsConverter {

    private static final Logger logger = Logger.getLogger(ManuscriptsConverter.class.getName());
    private static final String PROP_CONVERTED_DIR = "Convertor.convertedDir";
    private static final String PROP_TEI2MODS_MONOGRAPH_XSLT_FILE = "Convertor.monograph.tei2mods";
    private static final String PROP_MARC2OAIDC_MONOGRAPH_XSLT_FILE = "Convertor.marc2oaiDcXslt";
    private static final String PROP_KRAMERIUS_URL = "Kramerius.url";
    private static final String PROP_ALEPH_URL = "Aleph.url";

    private final File convertedDir;
    private final MonographBuilder monographBuilder;
    private final ClassicLinkPageBuilder linkPageBuilder;
    private final ImageServerPageBuilder imageServerPageBuilder;

    public ManuscriptsConverter(Properties properties) throws Exception {
        PropertyLoader propertyLoader = new PropertyLoader(properties);
        this.convertedDir = propertyLoader.loadDir(PROP_CONVERTED_DIR);
        File monographTei2modsXsltFile = propertyLoader.loadFile(PROP_TEI2MODS_MONOGRAPH_XSLT_FILE, true);
        File monographMarc2dcXsltFile = propertyLoader.loadFile(PROP_MARC2OAIDC_MONOGRAPH_XSLT_FILE, true);
        String krameriusUrl = propertyLoader.loadString(PROP_KRAMERIUS_URL);
        String alephUrl = propertyLoader.loadString(PROP_ALEPH_URL);
        this.monographBuilder = new MonographBuilder(monographMarc2dcXsltFile, monographTei2modsXsltFile, krameriusUrl, alephUrl);
        this.linkPageBuilder = new ClassicLinkPageBuilder(properties);
        this.imageServerPageBuilder = new ImageServerPageBuilder(properties);
    }

    public String convertToFoxmlSet(ManuscriptData mnsData, boolean createInternalParts, String monographUuid, Model model) throws FileNotFoundException, DocumentException {
        ManuscriptConverter manuscript = new ManuscriptConverter(mnsData, convertedDir, createInternalParts, monographUuid, model);
        AbstractPageBuilder pageBuilder = selectPageBuilder(mnsData);
        manuscript.buildFoxmlSet(monographBuilder, pageBuilder);
        return manuscript.getMonographPid();
    }

    private AbstractPageBuilder selectPageBuilder(ManuscriptData mnsData) {
        if (mnsData.isInImageServer()) {
            return imageServerPageBuilder;
        } else {
            return linkPageBuilder;
        }
    }
}
